package com.baor.controller;


import com.baor.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${upload.file.location}")
    private String uploadFileLocation;

    @RequestMapping("/upload")
    public AjaxResult fileUpload(@RequestParam(name = "file", required = false) MultipartFile file) throws IOException {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
        String name = UUID.randomUUID().toString().replace("-", "");
        String fileName = name + suffix;

        File upLoadFileLocation = new File(uploadFileLocation);
        if (!upLoadFileLocation.exists()) {
            upLoadFileLocation.mkdirs();
        }
        File newFile = new File(uploadFileLocation + fileName);
        System.out.println(newFile);
        file.transferTo(newFile);
        return AjaxResult.success(fileName);
    }
    //http://localhost:8082/file/download/cd29371fb62d46228ecde7c5a2dc3369.jpg
    @RequestMapping("/download/{imageName}")
    public void downLoad(@PathVariable String imageName, HttpServletResponse response) throws IOException {
        InputStream inputStream = new FileInputStream(uploadFileLocation + imageName);
        response.setContentType("image/jpeg");
        ServletOutputStream outputStream = response.getOutputStream();
        int count = 0;
        byte[] bytes = new byte[1024];
        while ((count = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
    }
}

